package com.zhang.service.impl;

import com.zhang.dao.AddressMapper;
import com.zhang.entity.Address;
import com.zhang.service.AddressService;
import com.zhang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class AddressServiceImpl implements AddressService {
    @Override
    public void insert(Address address) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            AddressMapper dao = sqlSession.getMapper(AddressMapper.class);
            dao.insert(address);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    @Override
    public List<Address> selectAll(int uid) {
        SqlSession sqlSession = null;
        List<Address> addressList = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            AddressMapper dao = sqlSession.getMapper(AddressMapper.class);
            addressList = dao.selectAll(uid);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
        return addressList;
    }

    @Override
    public void updateDelStatus(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            AddressMapper dao = sqlSession.getMapper(AddressMapper.class);
            dao.updateDelStatus(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

    @Override
    public void updateSelStatus(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            AddressMapper dao = sqlSession.getMapper(AddressMapper.class);
            dao.updateSelStatus0();
            dao.updateSelStatus1(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
}
